package singleton;

import java.io.Serializable;

/**
 * 懒汉式 DCL(Double Checked Lock),双检锁解决线程安全
 */
public class Singleton4 implements Serializable {
    private Singleton4(){
        System.out.println("private Singleton4()");
    }

    private static volatile Singleton4 INSTANCE = null;//可见性，有序性，加入volatile防止指令重排

    //加锁之前先判断，只有当INSTANCE还未创建阶段才会加锁，一旦INSTANCE创建完毕，则直接返回，提高了性能
    public static  Singleton4 getInstance(){
        if(INSTANCE == null){
            synchronized (Singleton4.class){
                if(INSTANCE == null){
                    INSTANCE = new Singleton4();
                }

            }
        }
        return INSTANCE;
    }

    //防止反序列化破环单例
    public Object readResolve(){
        return INSTANCE;
    }
}
